//
//  PhotoBrowserViewController.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/21.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD

private let cellIdentifier = "photoCellIdentifier"

class PhotoBrowserViewController: UIViewController,UICollectionViewDataSource {
    // 所有图像的数组
    var imgUrls : [NSURL]?
    
    // 选中照片索引
    var selectIndex : Int = 0 {
        didSet {
            println("设置索引照片\(selectIndex)")
        }
    }
    
    // collectionView 的布局
    lazy var layout : UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        return layout
        }()
    
    // collectionView
    lazy var collectionView : UICollectionView = {
        var cv = UICollectionView(frame: self.view.bounds, collectionViewLayout: self.layout)
        cv.dataSource = self
        
        cv.pagingEnabled = true
        return cv
        }()
    
    // 关闭和保存按钮
    lazy var closeBtn : UIButton = {
        return self.createButton("关闭")
    }()
    
    lazy var saveBtn : UIButton = {
        return self.createButton("保存")
    }()
    
    override func loadView() {
        view = UIView(frame: UIScreen.mainScreen().bounds)
        
        view.addSubview(collectionView)
        
        // 给按钮注册事件
        closeBtn.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        
        closeBtn.setTranslatesAutoresizingMaskIntoConstraints(false)
        saveBtn.setTranslatesAutoresizingMaskIntoConstraints(false)
        
        // 设置布局属性
        var cons = [AnyObject]()
        
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:|-16-[closeBtn(80)]-16-[saveBtn(80)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["closeBtn" : closeBtn, "saveBtn" : saveBtn])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:[closeBtn]-20-|", options: NSLayoutFormatOptions(0), metrics: nil, views: ["closeBtn" : closeBtn])
        
        cons.append(NSLayoutConstraint(item: saveBtn, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: closeBtn, attribute: NSLayoutAttribute.CenterY, multiplier: 1.0, constant: 0))
        
        view.addConstraints(cons)
    }
    
    // 穿件按钮控件
    private func createButton(title : String) -> UIButton {
        let btn = UIButton()
        btn.setTitle(title, forState: UIControlState.Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        btn.backgroundColor = UIColor.brownColor()
        view.addSubview(btn)
        
        return btn
    }
    
    // 关闭按钮
    func close(){
        closeBtn.hidden = true
        saveBtn.hidden = true
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 保存按钮
    private func sava (){
        let cell = collectionView.visibleCells().last as! PhotoBrowserCell
        
        //        if let image = cell.viewerVC.
    }
    
    //
    override func viewDidLoad() {
        super.viewDidLoad()
        // 注册可重用cell
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: cellIdentifier)
    }
    
    // 滚动到指定索引
    private func scrollSelectIndex(){
        // 获取路径
        let path = NSIndexPath(forItem: selectIndex, inSection: 0)
        // 滚动到指定路径
        collectionView.scrollToItemAtIndexPath(path, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
    }
    
    /// 在位置发生改变的时候调用
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        scrollSelectIndex()
    }
    
    
    // MARK: - 数据源方法
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        println("-=-=-=-=-=-=-\(imgUrls?.count)")
        return self.imgUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! PhotoBrowserCell
        
        cell.backgroundColor = UIColor(red: rndColor(), green: rndColor(), blue: rndColor(), alpha: 1)
        cell.imageUrl = imgUrls![indexPath.item]
        
        // 一定要添加子控制器
        if !(childViewControllers as NSArray).containsObject(cell.viewerVC!) {
            addChildViewController(cell.viewerVC!)
        }
        
        return cell
    }
    
    func rndColor() -> CGFloat {
        return CGFloat(arc4random_uniform(256)) / 255
    }
}

class PhotoBrowserCell: UICollectionViewCell {
    
    var viewerVC : PhotoViewerViewController?
    var imageUrl : NSURL?{
        didSet{
            viewerVC?.imageUrl = imageUrl
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = UIColor.clearColor()
        
        viewerVC = PhotoViewerViewController()
        // 此处设置应为bounds  不应该是frame  否则会出现图片每两张显示一张的情况  就是有一张看不到
        viewerVC!.view.frame = bounds
        
        println("--------\(frame)")
        println("========\(bounds)")
        
        self.addSubview(viewerVC!.view)
//        self.view.addSubview(viewerVC!.view)
    }
    
    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
}